﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace 线程测试
{
    public partial class Form1 : Form
    {
        Dictionary<string, Thread> ThreadMana = new Dictionary<string, Thread>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread th = new Thread(CreateThread);
            th.IsBackground = true;
            th.Start();
        }

        private void CreateThread()
        {
            int threadIndex = 0;
            while(true)
            {
                try {
                    if (threadIndex > 0) {
                        if(ThreadMana.ContainsKey((threadIndex-1).ToString()) == true)
                        {
                            Thread thd = ThreadMana[(threadIndex - 1).ToString()];
                            thd.Abort();
                            ThreadMana.Remove((threadIndex - 1).ToString());
                        }
                    }
                    Thread th = new Thread(ThreadTest);
                    th.IsBackground = true;
                    ThreadMana.Add(threadIndex.ToString(),th);
                    th.Start(threadIndex.ToString());
                    Thread.Sleep(30);
                    threadIndex++;
                } catch { }
            }
        }


        private void ThreadTest(object obj)
        {
            string sIndex = obj as string;
            while(true)
            {
                try {
                    this.Invoke(new EventHandler(delegate {
                        label1.Text = sIndex.ToString();
                    }));
                    Thread.Sleep(100);
                } catch (Exception ex){
                    this.Invoke(new EventHandler(delegate
                    {
                        label2.Text = ex.Message + ":" + sIndex;
                    }));
                }
            }
        }

    }
}
